﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft
{
    public class DictionaryHelper
    {
        /// <summary>
        /// 从运行时对象的公共属性读取一个字典
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Dictionary<string, object>? FromObject(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            var t = obj.GetType();
            Dictionary<string, object> dict = new Dictionary<string, object>();
            foreach (var p in t.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
                var v = p.GetValue(obj, null);
                dict[p.Name] = v;
            }
            return dict;
        }
        /// <summary>
        /// 合并两个字典，如有重复键，用后一个字典覆盖前一个的相同键。
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="dic1"></param>
        /// <param name="dic2"></param>
        /// <returns></returns>
        public static Dictionary<TKey, TValue> Union<TKey, TValue>(Dictionary<TKey, TValue> dic1, Dictionary<TKey, TValue> dic2)
        {
            Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
            foreach (var item in dic1)
            {
                dict[item.Key] = item.Value;
            }
            foreach (var item in dic2)
            {
                dict[item.Key] = item.Value;
            }
            return dict;
        }
    }
}
